#!/bin/sh
set -eu

BASE_URL='https://www.internic.net/domain'
destdir=${DNS_ROOT_HINTS_DIR:-"/usr/share/dns-root-hints"}

if ! [ -w "$destdir" ]; then
	echo 'Needs to run as root.' >&2
	exit 1
fi

tmpdir=$(mktemp -d)

cleanup() {
	rm "$tmpdir"/* 2>/dev/null || true
	rmdir "$tmpdir" || true
}
trap cleanup EXIT HUP INT TERM

for f in named.root named.root.sig; do
	curl -sLR "$BASE_URL/$f" -o "$tmpdir/$f"
done

read_version() {
	sed -En 's/.*related version of root zone:\s*([0-9]{10}).*/\1/p' "$1"
}
# compare new and current versions
new_ver=$(read_version "$tmpdir"/named.root)
cur_ver=$(read_version "$destdir"/named.root)

echo "Version $cur_ver <- Installed"
echo "Version $new_ver <- Downloaded"

# update to new version if needed
if [ "$new_ver" != "$cur_ver" ]; then
	gpgv --keyring "$destdir"/verisign-grs-nstld-key.gpg \
		"$tmpdir"/named.root.sig "$tmpdir"/named.root || exit 10

	mv "$tmpdir"/named.root "$destdir"/named.root
	mv "$tmpdir"/named.root.sig "$destdir"/named.root.sig

	printf '\nZone file updated.\n\n'
else
	printf '\nZone file already up-to-date.\n\n'
fi
